<?php
/**
 * Created by PhpStorm.
 * User: jh
 * Date: 2018-03-20
 * Time: 17:09
 */

namespace frontend\controllers;


use common\models\Feedback;
use common\services\FrontendMenuServices;
use common\services\SinglePageService;
use frontend\base\BaseFrontController;
use Yii;

class PageController extends BaseFrontController
{

    public function actionIndex()
    {
        $code = Yii::$app->request->get('code');
        if (empty($code)) {
            $this->redirect('/');
        }

        $success = 'False';
        $error = '';
        $feedback = '';
        if ($code == 'feedback') {
            $feedback = new Feedback();
            if (Yii::$app->request->isPost) {
                if (!Yii::$app->user->isGuest) {
                    $feedback->user_id = Yii::$app->user->getId();
                }
                if ($feedback->load(Yii::$app->request->post()) && $feedback->save()) {
                    $success = 'True';
                    $url = Yii::$app->urlManager->createUrl(['page/'.$code, 'status' => $success]);
                    $this->redirect($url);
                    Yii::$app->end();
                    //$feedback = new Feedback();
                } else {
                    $error = $feedback->errors;
                }
            }else{
                $status = Yii::$app->request->get('status');
                if ($status == 'True') {
                    $success = $status;
                }
            }
        }

        $pageService = new SinglePageService();
        $model = $pageService->getSinglePageByCode($code);
        if (empty($model))
            $this->redirect('/');
        $parentPageService = new FrontendMenuServices();
        $data = $parentPageService->getParentByCode($model['code']);
        return $this->render('index', [
            'model' => $model,
            'data' => $data,
            'code' => $code,
            'success' => $success,
            'error' => $error,
            'feedback' => $feedback,
        ]);
    }

}